﻿// CharacterBody.cs
//
// This file is part of the QuickStart Engine. However, it was based directly off of code
// from JigLibX's codeplex site, http://jiglibx.codeplex.com/.

using System;

using Microsoft.Xna.Framework;

using JigLibX.Physics;
using JigLibX.Collision;
using JigLibX.Math;

namespace Alex_s_Dream_The_Toy_World
{
    public class CharacterBody : Body
    {
        public CharacterBody()
            : base()
        {
        }
 
        public Vector3 DesiredVelocity { get; set; }
 
        private bool doJump = false;
 
        public void DoJump()
        {
            doJump = true;
        }
 
        public override void AddExternalForces(float dt)
        {
            ClearForces();
 
            if (doJump)
            {
                foreach (CollisionInfo info in CollisionSkin.Collisions)
                {
                    Vector3 N = info.DirToBody0;
                    if (this == info.SkinInfo.Skin1.Owner)
                        Vector3.Negate(ref N, out N);
 
                    if (Vector3.Dot(N, Orientation.Up) > 0.7f)
                    {
                        Vector3 vel = Velocity; 
                        vel.Y = 50.0f;
                        Velocity = vel;
                        break;
                    }
                }

                doJump = false;
            }
 
            // Very important
            AngularVelocity = Vector3.Zero;

            //Vector3 deltaVel = Vector3.Zero;
            
            //if ( DesiredVelocity.X == 0.0f && DesiredVelocity.Z == 0.0f ) 
            //{
                //Velocity = new Vector3(Velocity.X * (1 - (5 * dt)), Velocity.Y, Velocity.Z * (1 - (5 * dt)) );
            //}
           // else 
           // {
            //    deltaVel = DesiredVelocity - Velocity;
            //}
                Velocity += DesiredVelocity;
            DesiredVelocity = Vector3.Zero;
 
            //JiggleMath.NormalizeSafe(ref deltaVel);
 
            //deltaVel.Y = 0.0f;

            //deltaVel *= 10.0f;

            Vector3 velocityNoY = Velocity;
            velocityNoY.Y = 0;
 
            float forceFactor = 2000.0f;
            AddWorldForce((-velocityNoY * (1 - (5 * dt))) * Mass * dt * forceFactor);
 
            AddGravityToExternalForce();
        }
    }
}
